﻿

import Request from '../../base/request.js'
import Storage from '../../base/storage.js'
import { imageBaseUrl, queryURLParams, DeleteFormFile, DeleteFormFileItem, isImageFile, downloadfun } from "../../base/utils.js"
const Composition = (proxy) => {
    const data = reactive({
        proxy: "",
        type: "",
        fileOpen: false,
        plan: "",
        subform: {
            Remark:""
        },
        TotalScoreall:0,
        isEdit: false,
        isSave: false,
        listInfo: {},
        previewShow: false,
        imgUrl: "",
        isImage:true,
        form: {
            plan: null,
            year: "",
            person: "",
            duty: "",
            subdept: ""

        },
        mform: {
            title: null,
            month: "",
            person: "",
            dept: "",
            duty: "",
            rate: 1,
            type:""
        },
        ScoreRate:1,
        uploadLock:false,
        totala: 0,
        totals: 0,
        TotalScore: 0,
        i: 0,
        is: 0,
        iss: 0,
        planList: [],
        list: [

        ],
        activeKey: [0, 1],
        messageTest: "",
        formState: {
            dept: "",
            name: "",
            job: "",
            role: "",
            tel: "",
        },
        chooseFiles: [],
        deptList: [
  
        ],
        urlParams: {

        },
        monthList: [
            { label: '1月', value: '1' },
            { label: '2月', value: '2' },
            { label: '3月', value: '3' },
            { label: '4月', value: '4' },
            { label: '5月', value: '5' },
            { label: '6月', value: '6' },
            { label: '7月', value: '7' },
            { label: '8月', value: '8' },
            { label: '9月', value: '9' },
            { label: '10月', value: '10' },
            { label: '11月', value: '11' },
            { label: '12月', value: '12' },
        ],
        mlist:[],
        pagination: {
            total: 0,
            loading: true,
            current: 1,
            pageSize: 10,
            showTotal: total => `总共 ${total} 项`,
            defaultPageSize: 10,
            // pageSizeOptions: ['5', '10', '15', '20'], // 可不设置使用默认
            showSizeChanger: true, // 是否显示pagesize选择
            showQuickJumper: false, // 是否显示跳转窗
        },


        memberList: [],

        chooseMember: {},


        rules: {
            dept: [{ required: true, message: '请选择部门', trigger: 'change' }],
            name: [{ required: true, message: '请选择成员', trigger: 'change' }],

        },
        opType: "",
        confirmShow: false,
        delId: "",

        open: false,

        queryParams: {
            role: "",
            dept: "",
        },
        statusList: [
            { name: '组长', code: '0' },
            { name: '组员', code: '1' },

        ],


        columns: [
            {
                title: '序号',
                dataIndex: 'index',
                key: 'index',
                align: 'center',
                width: 80,
                customRender: (text, record, index) => {
                    return text.index + 1
                },
            },
            {
                title: '应用模块',
                dataIndex: 'a',
                key: 'a',
                align: 'center',
                customRender: function ({ text, record, index, column }) {
                    let linkBtn = h(antd.Button, { type: 'link' }, () => text)


                    return linkBtn
                }


            },
            {
                title: '考评扣分',
                dataIndex: 'b',
                key: 'b',
                align: 'center',
                customRender: function ({ text, record, index, column }) {

                    let numberInput = h(antd.InputNumber, { style: 'width:140px', placeholder: "请输入考评扣分", min: 0, max: 100 }, () => text)


                    return numberInput
                }
            },
            {
                title: '扣分缘由',
                dataIndex: 'c',
                key: 'c',
                align: 'center',
                customRender: function ({ text, record, index, column }) {
                    let textArea = h(antd.Textarea, { placeholder: "请输入扣分缘由", autoSize: { minRows: 2, maxRows: 5 } }, () => text)
                    return textArea
                }
            },

        ],
        dataSource: [],
        fileList: [],
     
        itemRender: (data) => {
            let uid = data.file.uid
            const text = h('div', { style: 'cursor:pointer;margin-left:10px' }, data.file.name)
            const previewBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnPreview(uid, 1) }, src: "../Bussiness/img/svg/preview.svg", width: 20, height: 22 }, '预览')
            const downloadBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDownLoad(uid, 1) }, src: "../Bussiness/img/svg/download.svg", width: 20, height: 22 }, '下载')
            const deleteBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDelete(uid, 1) }, src: "../Bussiness/img/svg/delete.svg", width: 18, height: 22 }, '删除')
            var btns = h('div', { style: "display:flex;margin-left:10px" }, [
                isImageFile(data.file.url)?  previewBtn:null,
                downloadBtn,
                deleteBtn
            ])

            return h('div', { style: 'margin-top:10px; width:100%;align-items:center; display:flex;justify-content:space-between' }, [
                text, btns
            ])

        },
    })
    let params = toRefs(data)

    const methods = {
        filterOption: (val, type) => {
            return `${type.label}`.includes(`${val || ''}`)
        },
        handleChange: (info) => {
            if (!params.uploadLock.value) {
                params.uploadLock.value = true
                let formData = new FormData();
                formData.append('nfile', info.file.originFileObj)
                formData.append('uid', info.file.originFileObj.uid)
                Request({
                    url: "/download/uploadfile?Path=Performance",
                    method: 'post',
                    data: formData
                }).then(res => {


                    params.uploadLock.value = false
                    if (params.type.value == 0) {
                        let item = params.mlist.value[params.i.value].NodeList
                        [params.is.value].ItemFileList.find(e => e.uid == res.Data[0].uid)
                        item.url = imageBaseUrl + res.Data[0].FilePath.split('../..')[1]
                        item.FileId = res.Data[0].FileId
                        item.FileName = res.Data[0].FileName

                    } else {

                        let item = params.list.value[params.i.value].NodeList
                        [params.is.value].NodeList
                        [params.iss.value].ItemFileList.find(e => e.uid == res.Data[0].uid)
                        item.url = imageBaseUrl + res.Data[0].FilePath.split('../..')[1]
                        item.FileId = res.Data[0].FileId
                        item.FileName = res.Data[0].FileName
                    }

                })

            }

        },

        export: () => {
            params.uploadLock.value = true
            html2canvas(document.querySelector("#target")).then(async (canvas) => {
       

                // 将 canvas 转换为 Blob
                const blob = await new Promise((resolve, reject) => {
                    canvas.toBlob(resolve, 'image/png');
                });

                // 创建 FormData 对象
                const formData = new FormData();
                formData.append('file', blob, 'pdf.png');

                Request({
                    url: "/download/uploadfile?Path=toPdf",
                    method: 'post',
                    data: formData
                }).then(res => {



     
                    Request({
                        url: `/Performance/ExportPdf?FileId=${res.Data[0].FileId}`,
                        method: 'post',
                  
                        }).then(res => {


                            downloadfun('报表', res.Data)

                            
                            params.uploadLock.value = false

                })


 



           
                })
            });
        },

        handleChange1: (info) => {

            if (!params.uploadLock.value) {
                params.uploadLock.value = true

                let formData = new FormData();
                formData.append('nfile', info.file.originFileObj)
                formData.append('uid', info.file.originFileObj.uid)
                Request({
                    url: "/download/uploadfile?Path=Performance",
                    method: 'post',
                    data: formData
                }).then(res => {
                    params.uploadLock.value = false
                    let item = params.fileList.value.find(e => e.uid == res.Data[0].uid)
                    item.url = imageBaseUrl + res.Data[0].FilePath.split('../..')[1]
                    item.FileId = res.Data[0].FileId
                    item.FileName = res.Data[0].FileName
                })
            }




        },
        downloadfun: (name, url) => {
            fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.blob();
                })
                .then(blob => {
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(blob);
                    link.download = name;
                    link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行

                    // 兼容性处理：对于不支持 click() 方法的浏览器
                    if (document.createEvent) {
                        const event = document.createEvent('MouseEvents');
                        event.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                        link.dispatchEvent(event);
                    } else {
                        link.click();
                    }

                    // 移除链接
                    document.body.removeChild(link);

                    // 释放 URL 对象
                    URL.revokeObjectURL(link.href);
                })
                .catch(error => {
                    console.error('There was a problem with the fetch operation:', error);
                });
        },
        setVisible: (value) => {
            params.previewShow.value = value;
        },

        getTemplate: () => {

            Request({
                url: "/performance/GetMonthReportInfo",
                method: 'post',

            }).then(res => {
                params.mlist.value = res.Data.ItemList[0].NodeList
                params.listInfo.value = res.Data.ItemList[0]
                params.TotalScoreall.value = res.Data.ItemList[0].TotalScore
                params.TotalScore.value = params.TotalScoreall.value

            })
        },
        btnPreview: (e, type) => {

            if (type) {
                let item = params.fileList.value.find(es => es.uid == e)
                params.imgUrl.value = item.url

                methods.setVisible(true)
                return
            }
            if (params.type.value == 0) {
                let item = params.chooseFiles.value.find(es => es.uid == e)
                params.imgUrl.value = item.url

                methods.setVisible(true)
            } else {
                let item = params.chooseFiles.value.find(es => es.uid == e)
                params.imgUrl.value = item.url

                methods.setVisible(true)
            }


        },

        btnDownLoad: (e, type) => {

            if (type) {

                let item = params.fileList.value.find(es => es.uid == e)
                const { name, url } = item
                methods.downloadfun(name, url)
                return
            }
            if (params.type.value == 0) {
                let item = params.chooseFiles.value.find(es => es.uid == e)
                const { name, url } = item
                methods.downloadfun(name, url)
            } else {
                let item = params.chooseFiles.value.find(es => es.uid == e)
                const { name, url } = item
                methods.downloadfun(name, url)
            }



        },
        btnDelete: async (e, type) => {

            if (type) {



                let ditem = params.fileList.value.filter(es => es.uid == e)[0]
                if (ditem && ditem.FileId) {
                    try {
                        let res = await DeleteFormFile(Request, ditem.FileId)
                        if (res) {
                            params.fileList.value = params.fileList.value.filter(es => es.uid != e)
                        }
                    }
                    catch (err) {
                        params.messageTest.value.success(err.Msg);

                    }
                }






                return
            }
            if (params.type.value == 0) {


                let ditem = params.mlist.value[params.i.value].NodeList
                [params.is.value].ItemFileList.filter(es => es.uid == e)[0]
                console.log(ditem, 'ditem')
                if (ditem && ditem.FileId) {
                    try {
                        let res = await DeleteFormFileItem(Request, ditem.FileId)
                        if (res) {
                            params.mlist.value[params.i.value].NodeList
                            [params.is.value].ItemFileList
                                = params.mlist.value[params.i.value].NodeList
                                [params.is.value].ItemFileList.filter(es => es.uid != e)
                            params.chooseFiles.value = params.chooseFiles.value.filter(es => es.uid != e)
                        }
                    }
                    catch (err) {
                        console.log(err)
                        params.messageTest.value.success(err.Msg);

                    }
                }


            } else {


                let ditem = params.list.value[params.i.value].NodeList
                [params.is.value].NodeList
                [params.iss.value].ItemFileList.filter(es => es.uid == e)[0]
                if (ditem && ditem.FileId) {
                    try {
                        let res = await DeleteFormFileItem(Request, ditem.FileId)
                        if (res) {

                            params.list.value[params.i.value].NodeList
                            [params.is.value].NodeList
                            [params.iss.value].ItemFileList = params.list.value[params.i.value].NodeList
                            [params.is.value].NodeList
                            [params.iss.value].ItemFileList.filter(es => es.uid != e)
                            params.chooseFiles.value = params.chooseFiles.value.filter(es => es.uid != e)
                        }
                    }
                    catch (err) {
                        params.messageTest.value.success(err.Msg);

                    }
                }






            }



        },

        planChange: (e) => {
            if (e) {
                Request({
                    url: "/Performance/GetSelfTempleteByPlan",
                    method: 'post',
                    params: {
                        Id: e
                    }

                }).then(res => {

                    params.list.value = res.Data[0].NodeList
                    params.TotalScore.value = res.Data[0].TotalScore

                })
            }

        },
        handleItemSave: (e, i) => {

            Request({
                url: "/Performance/UpdateMonthReportItem",
                method: 'post',
                data: e

            }).then(res => {
                params.messageTest.value.success(res.Msg);
                methods.init()
            })



        },
        handleFile: (i, is, iss) => {


            params.chooseFiles.value=[]
            params.fileOpen.value = true



            if (params.type.value == 0) {

                params.i.value = i
                params.is.value = is
                params.chooseFiles.value = params.mlist.value[i].NodeList
                [is].ItemFileList.map(e => {

                    e.url = e.url ? e.url : imageBaseUrl + e.FilePath.split('../..')[1]
                    e.FileId = e.FileId
                    e.name = e.FileName
                    e.isImage = isImageFile(e.url)
                    return {
                        ...e,


                    }
                })


            } else {
                params.chooseFiles.value = params.list.value[i].NodeList
                [is].NodeList
                [iss].ItemFileList.map(e => {

                    e.url = e.url ? e.url : imageBaseUrl + e.FilePath.split('../..')[1]
                    e.FileId = e.FileId
                    e.name = e.FileName

                    e.isImage = isImageFile(e.url)
                    return {
                        ...e,


                    }
                })
            }



        },

        ichange: () => {
            if (params.type.value == 0) {
                let f = params.mlist.value.map((e, i) => {

                    let ff = {

                    }
                    if (e.CalcType == 0) {
                        if (e.NodeList) {
                            let zz = e.NodeList.map(es => {

                                return es.ItemScore ? es.ItemScore * +params.mform.value.rate : 0
                            })
                            ff.sub = zz.reduce((prev, cur, index, arr) => {
                                return prev + cur
                            }, 0)
                        }
                    } else {
                        if (e.NodeList && e.NodeList.length != 0) {
                            let zz = e.NodeList.map(es => {
                                return es.ItemScore ? es.ItemScore : 0
                            })
                            ff.add = zz.reduce((prev, cur, index, arr) => {
                                return prev + cur
                            }, 0)
                        }
                    }

                    return ff
                })
                let totala = 0
                let totals = 0
                for (let e of f) {
                    if (e.add) {
                        totala += e.add
                    } else if (e.sub) { totals += e.sub }
                }
                params.totala.value = totala
                params.totals.value = totals

                params.TotalScore.value = params.TotalScoreall.value + params.totala.value - params.totals.value
            } else {
                let f = params.list.value.map((e, i) => {
                    let ff = {

                    }
                    if (e.CalcType == 0) {
                        if (e.NodeList) {
                            let zz = e.NodeList.map(es => {
                                if (es.NodeList) {
                                    let res = es.NodeList.map(ess => {
                                        return ess.SelfScore ? ess.SelfScore : 0
                                    })
                                    return res.reduce((prev, cur, index, arr) => {
                                        return prev + cur
                                    }, 0)
                                }
                            })
                            ff.sub = zz.reduce((prev, cur, index, arr) => {
                                return prev + cur
                            }, 0)
                        }
                    } else {
                        if (e.NodeList) {
                            let zz = e.NodeList.map(es => {
                                if (es.NodeList) {
                                    let res = es.NodeList.map(ess => {
                                        return ess.SelfScore ? ess.SelfScore : 0
                                    })
                                    return res.reduce((prev, cur, index, arr) => {
                                        return prev + cur
                                    }, 0)
                                }
                            })
                            ff.add = zz.reduce((prev, cur, index, arr) => {
                                return prev + cur
                            }, 0)
                        }
                    }

                    return ff
                })
                let totala = 0
                let totals = 0
                for (let e of f) {
                    if (e.add) {
                        totala += e.add
                    } else if (e.sub) { totals += e.sub }
                }
                params.totala.value = totala
                params.totals.value = totals
            }




        },
        handleDrop: (e) => {
            console.log(e, 'drag');
        },

        GetDepartmentConfig: (id) => {
            
            Request({
                url: "/Performance/GetDepartmentConfig",
                method: 'post',
                data: {
                    DepartmentId: id
                }

            }).then(res => {
                params.ScoreRate.value = res.Data.ScoreRate
                console.log(res,'res')
            })


        },



        upload: (i, is, iss) => {


         

            if (params.type.value == 0) {
                params.i.value = i
                params.is.value = is
    

                if (!params.mlist.value[params.i.value].NodeList
                [params.is.value].ItemFileList
               ) {
                    params.mlist.value[params.i.value].NodeList
                    [params.is.value].ItemFileList = []
                }

            } else {
       

                params.i.value = i
                params.is.value = is
                params.iss.value = iss

                if (!params.list.value[params.i.value].NodeList
                [params.is.value].NodeList
                [params.iss.value].ItemFileList) {
                    params.list.value[params.i.value].NodeList
                    [params.is.value].NodeList
                    [params.iss.value].ItemFileList = []
                }

            }




           
        },
        dChange: (e) => {
            const { id } = queryURLParams()
            if (id) {

                let item = params.deptList.value.find(es => es.value == e)

                params.mform.value.duty = item.duty
                params.mform.value.rate = item.rate

                params.mform.value.type = item.type
                methods.ichange()
            } else {
                let item = params.deptList.value.find(es => es.value == e)
     
                params.mform.value.duty = item.duty
                params.mform.value.rate = item.rate

                params.mform.value.type = item.type||'暂无数据'
                let year = dayjs(Date.now()).format('YYYY')

                let month = dayjs(Date.now()).format('M')

                params.mform.value.title = `${year}年度公司${month}月${item.label}月度考核表`
                methods.ichange()
            }

       
        },
        init: () => {
            if (proxy) {
                params.proxy.value = proxy
            }
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });
            let info = Storage.get('AccountInfo', true)
            const { type } = queryURLParams()

            params.form.value.person = `${info.UserName}(${info.UserNo})`
            params.form.value.subdept = info.DepartmentName
            params.form.value.duty = info.Manager || ""
            params.type.value = type
            Request({
                url: "/Account/createJwtToken",
                method: 'post',
                data: {
                    "userName": info && info.UserNo
                }
            }).then(res => {
                Storage.set('token', res.Data,true)
                methods.GetDepartmentConfig(info.DepartmentId)
                Request({
                    url: "/performance/GetDepartmentDetailList",
                    method: 'post',

                }).then(res => {

                    params.deptList.value = res.Data.map(e => {
                        return {
                            label: e.DepartmentName,
                            value: e.Id,
                            type: e.DepTypeName,
                            rate: e.ScoreRate,
                            duty: `${e.ManagerName}(${e.Manager})`
                        }
                    })
                    if (params.type.value == 0) {
                        const { id, isEdit } = queryURLParams()

                

                        









   
                        if (id) {
                            params.isSave.value=true

                            Request({
                                url: "/performance/GetMonthReportInfo",
                                method: 'post',
                                params: {
                                    FormId: id
                                }
                            }).then(res => {

                                const data = res.Data
                                params.mform.value.title = data.Title
                                params.mform.value.month = `${data.Months}月`
                                params.mform.value.dept = data.DepartmentId
                                params.subform.value.Remark = data.Remark
                                params.fileList.value = data.FileList && data.FileList.map(e => {
                                    e.FilePath = imageBaseUrl + e.FilePath.split('../..')[1]
                                    e.name = e.FileName
                                    e.url = e.FilePath
                                    return e
                                })
                                params.mlist.value = data.ItemList[0].NodeList
                                params.listInfo.value = data.ItemList[0]

                                params.TotalScoreall.value = data.ItemList[0].TotalScore

                                params.TotalScore.value = params.TotalScoreall.value

                   

                                methods.dChange(data.DepartmentId)
                                if (isEdit) {
                                    params.isEdit.value = !JSON.parse(isEdit)
                                }
                             
                                
                            })



                        }
                        else {
                            let year = dayjs(Date.now()).format('YYYY')
                            //params.TotalScoreall.value = data.ItemList[0].TotalScore

                            //params.TotalScore.value = params.TotalScoreall.value
                            let month = dayjs(Date.now()).format('M')

                            params.mform.value.title = `${year}年度公司${month}月某部月度考核表`
                            params.mform.value.month = `${month}月`
                            params.mform.value.dept = null
                            params.mform.value.person = info.UserName

                            methods.getTemplate()


                        }





                    } else {










                    }
                })
         



                Request({
                    url: "/Performance/GetSimplePlanList",
                    method: 'post',

                }).then(res => {

                    params.planList.value = res.Data.map(e => {
                        return {
                            label: `${e.Title}`,
                            value: e.Id
                        }
                    })


                    params.urlParams.value = queryURLParams()
                    params.form.value.plan = params.urlParams.value.id
                    methods.planChange(params.urlParams.value.id)

                })



            })


     

        },

        onSubmit: (Status) => {


     
         
                if (Status!= 0) {
                    if (params.fileList.value.length == 0) {
                        return params.messageTest.value.success('请上传附件');
                    }
                }

           
                const { plan } = params.form.value
                const { Remark } = params.subform.value
                const SelfTotalScore = params.TotalScore.value + params.totala.value - params.totals.value


                let ss = []
                for (let e of params.list.value) {
                    if (e.NodeList) {
                        e.NodeList.map(es => {
                            if (es.NodeList) {
                                es.NodeList.map(ess => {
                                    ss.push(ess)
                                })
                            }
                        })
                    }

                }


                let obj = {
                    model: {
                        "Years": "2024",
                        "PlanId": plan,
                        "Remark": Remark,
                        "SelfTotalScore": SelfTotalScore,//自评总分
                        "Status": Status
                    },
                    items: ss.map(e => {

                        return {
                            ...e,
                            FileList: e.fileList,
                            ContentId: e.Id
                        }
                    }),
                    FileList: params.fileList.value.map(e => e.FileId)
                }

                Request({
                    url: "/Performance/AddYearsReportForm",
                    method: 'post',
                    data: obj
                }).then(res => {
                    params.messageTest.value.success(res.Msg);
                    if (res.Code == 100) {
   setTimeout(() => {
                        methods.onBack()
                    }, 1500)
                    }
                 

                })
            
                      


     



        },
        onBack: () => {
            window.location.href = '/Performance/PerformanceMeansureNew'
        }


    }
    const template = {
        bottomBtns: {
            template: `<div class="w-full bg-[#eeeeee] h-50  flex  items-center justify-end">
                    <a-space>
  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(0)"
  >
        

 <a-button   :loading="uploadLock" type="primary">保存</a-button>
  </a-popconfirm>
  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(2)"
  >


   <a-button :loading="uploadLock" type="primary">提交</a-button>
  </a-popconfirm>

                     
                        <a-button v-on:click="onBack">返回</a-button>
                    </a-space>
                </div>`,
            setup() {

                return {
                    ...params,
                    ...methods,
                };
            }

        }
    }


    //let template = toRefs(vtemplate)
    return { // 返回对象给模板

        ...params,
        ...methods,
        template

    }
}


export default Composition





